package com.fingard.util.secret.salary;

import org.apache.commons.codec.binary.Hex;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;

/**
 * Created by F on 2019/1/5.
 */
public class DESUtil {
    public static void main(String[] args) {

        //测试代码
        String sb="6217000010081785928_1.00";
        String key="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaSoQ5ge0FJ82RPNriht2wCyFCAgPG1gLq5IhpBxyoMgc2asdadsdsssssssssssssssssssssssssssssdsdsaaaaaddd=";
        String encryptMode=jdkDESEncryptMode(sb, key);
        System.out.println("密文长度："+encryptMode.length()+"密文："+encryptMode);
        String desDecryptMode=jdkDESDecryptMode(encryptMode,key);
        System.out.println("明文："+desDecryptMode);
    }

    /**
     * 加密
     * @param str 待加密字符串
     * @param key 加密KEY
     * @return 密文字符串
     */
    public static String jdkDESEncryptMode(String str,String key){
        try {
            //key转换成密钥
            DESedeKeySpec desKeySpec=new DESedeKeySpec(key.getBytes());
            SecretKeyFactory factory=SecretKeyFactory.getInstance("DESede");
            SecretKey key2 = factory.generateSecret(desKeySpec);      //转换后的密钥

            //加密
            Cipher cipher=Cipher.getInstance("DESede/ECB/PKCS5Padding");  //算法类型/工作方式/填充方式
            cipher.init(Cipher.ENCRYPT_MODE, key2);   //指定为加密模式
            byte[] result=cipher.doFinal(str.getBytes());
            //System.out.println("jdk3DES加密: "+ Hex.encodeHexString(result));  //转换为十六进制
            return Hex.encodeHexString(result);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解密
     * @param str 待解密字符串
     * @param key 解密KEY
     * @return 明文字符串
     */
    public static String jdkDESDecryptMode(String str,String key){
        try {
            //key转换成密钥
            DESedeKeySpec desKeySpec=new DESedeKeySpec(key.getBytes());
            SecretKeyFactory factory=SecretKeyFactory.getInstance("DESede");
            SecretKey key2 = factory.generateSecret(desKeySpec);      //转换后的密钥
            //解密
            Cipher cipher=Cipher.getInstance("DESede/ECB/PKCS5Padding");  //算法类型/工作方式/填充方式
            //解密
            cipher.init(Cipher.DECRYPT_MODE,key2);  //相同密钥，指定为解密模式
            byte[] result = cipher.doFinal(Hex.decodeHex(str.toCharArray()));   //根据加密内容解密
            //System.out.println("jdk3DES解密: "+new String(result));  //转换字符串
            return new String(result);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}
